import type { ComponentInternalInstance } from "vue";
type InstanceOrNull = ComponentInternalInstance | undefined | null;
type EventChannelType = "off" | "on" | "once";
type EventChannelAction = {
    name: string;
    cb: (...args: any) => void;
};
function safeEventChannel(ins?: InstanceOrNull) {
    let proxy = ins?.proxy;
    if (!proxy) {
        return undefined;
    }
    // @ts-ignore
    let getOpenerEventChannel = proxy["getOpenerEventChannel"];
    if (typeof getOpenerEventChannel !== "function") {
        return undefined;
    }
    let eventChannel = (proxy as any).getOpenerEventChannel();
    return eventChannel;
}

function safeEventChannelEvent(
    type: EventChannelType,
    ins?: InstanceOrNull,
    action?: EventChannelAction
) {
    let channel = safeEventChannel(ins);
    if (!channel) {
        return;
    }
    if (!action) {
        return channel;
    }
    let targetFn = channel[type];
    if (!targetFn) {
        return channel;
    }
    targetFn.call(channel, action.name, action.cb);
    return channel;
}

function safeEventChannelOnce(ins?: InstanceOrNull, action?: EventChannelAction) {
    return safeEventChannelEvent("once", ins, action);
}

function safeEventChannelOn(ins?: InstanceOrNull, action?: EventChannelAction) {
    return safeEventChannelEvent("on", ins, action);
}

function safeEventChannelOff(ins?: InstanceOrNull, action?: EventChannelAction) {
    return safeEventChannelEvent("off", ins, action);
}

export { safeEventChannel, safeEventChannelOnce, safeEventChannelOn, safeEventChannelOff };
